module.exports = () => {
  return async function (ctx, next) {
    try {
      if (ctx.request.header.token) {
        const token = ctx.request.header.token;
        const data = await ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
        const tokenDate = await ctx.model.Tokendate.findOne({
          where: {
            userId: data.userId
          },
          attributes: ["tokenDate"]
        });
        if (tokenDate.tokenDate !== data.tokenDate) {
          ctx.body = {
            code: 405,
            msg: "账号已经在另外一台登录"
          };
          return;
        }
        await next();
      } else {
        ctx.body = {
          code: 403,
          msg: "没有权限"
        };
      }
    } catch (err) {
      let fail =
        err.name === "TokenExpiredError"
          ? "token 已过期! 请重新获取令牌"
          : "Token 令牌不合法!";
      ctx.body = {
        code: 403,
        message: fail
      };
    }
  };
};
